package ch.headshot.photomap.client.gpx.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import ch.headshot.photomap.client.gpx.Link;
import ch.headshot.photomap.client.gpx.WayPoint;

import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.NodeList;

public class WayPointImpl implements WayPoint {

	private static final String LAT = "lat";
	private static final String LON = "lon";
	private static final String LINK = "link";

	private final Element wpt;
	private Double latitude;
	private Double longitude;

	public WayPointImpl(Element wpt) {
		this.wpt = wpt;
	}

	@Override
	public String toString() {
		StringBuffer b = new StringBuffer("<trkpt ");
		b.append(LAT + "=" + getLatitude());
		b.append(" " + LON + "=" + getLongitude());
		b.append("</trkpt>");
		return b.toString();
	}

	public Double getLatitude() {
		if (latitude == null) {
			latitude = Double.valueOf(wpt.getAttribute(LAT));
		}
		return latitude;
	}

	public Double getLongitude() {
		if (longitude == null) {
			longitude = Double.valueOf(wpt.getAttribute(LON));
		}
		return longitude;
	}

	public List<Link> getLinks() {
		List<Link> result = new ArrayList<Link>();
		NodeList rtes = wpt.getElementsByTagName(LINK);
		for (int i = 0; i < rtes.getLength(); i++) {
			result.add(new LinkImpl((Element) rtes.item(i)));
		}
		return result;
	}

	public Date getTime() {
		NodeList time = wpt.getElementsByTagName("time");
		if (time.getLength() < 1) {
			return null;
		}
		String nodeValue = time.item(0).getNodeValue();
		// TODO parse date
		return new Date(nodeValue);
	}

	public void setLatitude(Double latitude) {
		this.latitude = latitude;
	}

	public void setLongitude(Double longitude) {
		this.longitude = longitude;
	}

	public WayPoint copy() {
		return new WayPointImpl(wpt);
	}
}
